/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Apr 4, 2012  12:36:50 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.mm.outbound
 * File Name : VwSyncRequestPaymentService.java
 * TODO
 */
package sap.business.mm.outbound;

import java.util.ArrayList;
import java.util.List;
import jpa.entitys.synchro.staging.MmLivcontractorDeduct;
import jpa.entitys.synchro.staging.MmLivcontractorOutb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.MmLivcontractorOutbServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoStructure;
import com.sap.conn.jco.JCoTable;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;

/**
 * @author chatree
 *
 */
public class VwSyncRequestPaymentService extends SynchroOutAbstract {
	private static final Logger log = Logger.getLogger(VwSyncRequestPaymentService.class);
	private static MmLivcontractorOutbServices MmLivcontractorOutbServ;
	private String table_IM_LIV_MAIN_DEDUCT = "T_LIV_MAIN_DEDUCT";

	/**
	 * 
	 * Date =Nov 12, 2013 : 2:35:00 PM 
	 * CreateBy=Chatree Siangklom
	 * VwSyncRequestPaymentService
	 * TODO
	 */
	public VwSyncRequestPaymentService() {
		try {
			
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	/**
	 * 
	 * Date =Nov 12, 2013 : 2:35:02 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param jcoFunction
	 * @param jcoTable
	 * @param jCoStructure
	 * @param value_list
	 * @param jcoTableDeduct
	 * @param mmlivDeduct
	 * @throws Exception
	 */
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, JCoStructure jCoStructure, List<?> value_list, JCoTable jcoTableDeduct, List<MmLivcontractorDeduct> mmlivDeduct) throws Exception {
		try{
			
			//Check Is not isEmpty is exit method.
			if(!jcoTable.isEmpty())
			{
				System.err.println("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");
				return;
			}	
			if(!jcoTableDeduct.isEmpty())
			{
				System.err.println("Bapi = "+ sap_bapi +", table "+ table_IM_LIV_MAIN_DEDUCT +" is not Empty ");
				return;
			}	
			
			if(!CommonService.IsNull(value_list)){
				jCoStructure.clear();
				System.out.println("value_list.size : " + value_list.size() +  " //table.getNumRows : " + jcoTable.getNumRows());		
				MmLivcontractorOutb modelObj = (MmLivcontractorOutb)value_list.get(0);
				jCoStructure.setValue("BLDAT", modelObj.getRequestDate());
				jCoStructure.setValue("BUDAT", modelObj.getRequestDate());								
				jCoStructure.setValue("BUKRS", modelObj.getSapCompanyCode());								
				jCoStructure.setValue("BUPLA", "0000");								
				jCoStructure.setValue("XBLNR", modelObj.getRefInvoiceNo());								
				jCoStructure.setValue("WAERS", modelObj.getCurrency());								
				jCoStructure.setValue("BKTXT", modelObj.getRequestNo());								
				//jCoStructure.setValue("MWSKZ1", model.getTaxType());
				
				jCoStructure.setValue("MWSKZ1", "VX");  //Include Vat fix VX 				
				jCoStructure.setValue("REQTRACK_NO", modelObj.getRefContractNo());								
				jCoStructure.setValue("PO_AMOUNT", modelObj.getPaymentAmount());
				
				jcoTable.deleteAllRows();
				for (Object obj : value_list) 
		        {
					MmLivcontractorOutb model = (MmLivcontractorOutb)obj;
					System.out.println("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId()  + " -- DocumentNo = " +  model.getDocumentNo());
					
					jcoTable.appendRow();
					jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
					
					jcoTable.setValue("TRACK_NO", model.getRefContractNo());								
					
					//jcoTable.setValue("MATNR_PROMIS", CommonService.IsNullRNull(model.getInstallmentNumber()));							
					//Edit 2013-03-15
					//DR.TREE 
					//Support PO Multi line 
					jcoTable.setValue("MATNR_PROMIS", model.getInstallmentNumberStr());
					
					if(model.getUnitNumber() != null)
						jcoTable.setValue("ITMPLAN", model.getUnitNumber());
					else
						jcoTable.setValue("ITMPLAN", model.getBuildingCode());
					
					jcoTable.setValue("EBELN", "'");
					jcoTable.setValue("EBELP", "");
					jcoTable.setValue("WERKS", model.getSapPlantCode());
					jcoTable.setValue("RMWWR", "");
					jcoTable.setValue("PROGRESS", model.getActualWorkCompleted());
					jcoTable.setValue("PERIOD_AMOUNT", model.getInstallmentAmount());
					jcoTable.setValue("RETENTION_AMOUNT", model.getRetentionAmount());
					jcoTable.setValue("CONTRACT_AMOUNT", model.getContrGuaranteeAmount());
					jcoTable.setValue("PENALTY_AMOUNT", model.getPenaltyAmount());
					jcoTable.setValue("PROCESS_AMOUNT", model.getFee());
					jcoTable.setValue("PO_DEDUCT_AMOUNT", model.getPoDeductAmount());
					jcoTable.setValue("PO_DEDUCT_CONT", model.getPoDisAmount());
					jcoTable.setValue("PO_ADD_CONT", model.getPoAddAmount());					
					
					//*******************************************************************
					//For old Data (RMS) Y=IS PAID, N=New Data for PROMIS
					//SAP X = Are payable.
					jcoTable.setValue("FLAG", CommonService.IsNullRString(model.getPayableFlag()));
					//*******************************************************************
										
					//*************************************************************************************
					//Add 2012-09-18 Palith SAP Request for add, Meaw Meeting
					//Y=Deduc Contract Guarantee
					//N=Normal Contract Guarantee
					//PROMIS Default = N
					jcoTable.setValue("RET_CONTR_GUARAN", CommonService.IsNullRString(model.getReturnContractGuaranteeFlag()));
					//*************************************************************************************
					
					//Add New Field SAP Need to Know Document Status 
					//A=Approved, Z=Calcelled
					//DR.TREE, MEAW, WISAKA, PALITH, 
					//2013-01-15
					if(CommonService.IsNullRString(model.getStatus()).equals("Z"))
						jcoTable.setValue("STATUS_FLAG", "Z");
					
					//Palith Request RefType for [VO,CT,CW] ref gtalk
					//2013-03-30
					jcoTable.setValue("CONTRACT_TYPE", model.getRefType());
					
					//Dr.Tree
					//2013-04-05
					//support for request for installment 
					//TABLE : PAYMENT_REQUEST_INSTALLMENT field : (seq, installment_seq)
					jcoTable.setValue("SEQUENCE", model.getLineInstKey());
					
		        }
				
				//Deduct  List
				jcoTableDeduct.deleteAllRows();
				System.err.println("mmlivDeduct = " + CommonService.getSize(mmlivDeduct));
				if(CommonService.getSize(mmlivDeduct) > 0){
					for(MmLivcontractorDeduct value : mmlivDeduct){
						jcoTableDeduct.appendRow();
						jcoTableDeduct.setValue("REQUEST_NO", value.getRequestNo());	
						jcoTableDeduct.setValue("REF_CONTRACT_NO", value.getContractDocNo());	
						jcoTableDeduct.setValue("PLANT", value.getSapPlantCode());	
						
						//Modify : DR.TREE 
						//Date : 2013-06-28
						//jcoTableDeduct.setValue("DEDUCT_AMOUNT", value.getDeductAmount());
						jcoTableDeduct.setValue("DEDUCT_AMOUNT", value.getPayDeduct());
						
						jcoTableDeduct.setValue("DEDUCT_CONT_PROJ", value.getMainContractNo());	
						jcoTableDeduct.setValue("DEDUCT_CONT_NO", value.getMainContractDocNo());	
						
						//jcoTableDeduct.setValue("DEDUCT_INSTALL", value.getRefInstallmentNo());
						//Add 2013-03-21
						//DR.TREE
						jcoTableDeduct.setValue("DEDUCT_INSTALL", value.getInstallmentNumberStr());
						
						jcoTableDeduct.setValue("DEDUCT_UNIT", value.getUnitNumber());	
						jcoTableDeduct.setValue("DEDUCT_PLANT", value.getSapPlantCode());
						
						//Palith Request 
						//Add 2013-04-03
						//DR.TREE Modify
						jcoTableDeduct.setValue("LIFNR", value.getContractorCode());
					}
				}
			}
			
			super.SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
			
		}catch(Exception e)
		{			
			e.printStackTrace();
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			
			throw e;
		}
	}
	
	/**
	 * 
	 * Date =Nov 12, 2013 : 2:35:08 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param jcoTable_return
	 * @param mmlivDeduct
	 * @throws Exception
	 */
	public void CallbackMessageFromSap(JCoTable jcoTable_return, List<MmLivcontractorDeduct> mmlivDeduct) throws Exception {
		// TODO Auto-generated method stub
		List<MmLivcontractorOutb> lst = new ArrayList<MmLivcontractorOutb>();				
		if(jcoTable_return != null && jcoTable_return.isEmpty() == false)
		{
			System.out.println("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
			for(int i = 0; i < jcoTable_return.getNumRows(); i++)
			{
				jcoTable_return.setRow(i);			
				MmLivcontractorOutb model = MmLivcontractorOutbServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
				log.info(CommonJCOReturn.toString(jcoTable_return));
				
				if(model != null){
					model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
					model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
					model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
					model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
					model.setIsactive("Y");
					model.setIssync("Y");					
					lst.add(model);
				}
			}
			
			MmLivcontractorOutbServ.Updated(lst);
			
			//Update mmlivDeduct
			List<MmLivcontractorDeduct> NewmmlivDeduct = new ArrayList<MmLivcontractorDeduct>();
			if(CommonService.getSize(mmlivDeduct) > 0){
				for(MmLivcontractorDeduct value : mmlivDeduct){
					value.setIssync("Y");
					value.setIsactive("Y");				
					NewmmlivDeduct.add(value);
				}
				MmLivcontractorOutbServ.UpdatedDeduct(NewmmlivDeduct);
			}
		}else
			log.info(CommonJCOReturn.toString(jcoTable_return));
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	private void UpdateStagingWhenError(List<MmLivcontractorOutb> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<MmLivcontractorOutb> newlst = new ArrayList<MmLivcontractorOutb>();
				for(MmLivcontractorOutb model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new MmLivcontractorOutbServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	@Deprecated
	private List<MmLivcontractorOutb> Search() throws Exception 
	{
		try{
			
			String company = "SP";
			String project = "SPLVILLE-PRAGSA";
			String documentNo = "PB-1204-000001";
			String status = "A";
			String issync = "N";
			List<MmLivcontractorOutb> lst = MmLivcontractorOutbServ.findByDocumentNo(company, project, documentNo, status, issync);
			
			if(!CommonService.IsNull(lst))
				log.info(lst.size());
			else
				log.info(" else  ");
			
			return lst;
			
		}catch(Exception e)
		{

			log.error(e.getMessage());
			System.err.println(e.getMessage());
			
			throw e;
		}
		
	}
	
	public void SendToSAP(List<MmLivcontractorOutb> value_list, List<MmLivcontractorDeduct> mmlivDeduct) throws Exception {
		try{
			
			if(!CommonService.IsNull(value_list))
			{
				this.sap_bapi = "ZIN_MMIV_LIV";
				this.sap_structure = "IM_LIV_HEADER";
				this.sap_table = "T_LIV_ITEM";
				this.sap_table_return = "RETURN";					
				this.jco_conn  = new Connection();
				MmLivcontractorOutbServ = new MmLivcontractorOutbServices(this.emSynchro);
				
				//Get SAP BAPI function
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table or Structure
				JCoTable jcoTable = jco_conn.getTables(sap_table);
				JCoStructure jCoStructure = jco_conn.getImportStructure(sap_structure);				
				
				JCoTable jcoTableDeduct = jco_conn.getTables(table_IM_LIV_MAIN_DEDUCT);
				
				SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list, jcoTableDeduct, mmlivDeduct);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return, mmlivDeduct);
				
			}
		}catch(Exception e)
		{
			UpdateStagingWhenError(value_list, e);

			log.error(e.getMessage());
			System.err.println(e.getMessage());
			
			throw e;
		}
	}
	
	@Deprecated
	private void Start() throws Exception
	{
		this.sap_bapi = "ZIN_MMIV_LIV";
		this.sap_structure = "IM_LIV_HEADER";
		this.sap_table = "T_LIV_ITEM";
		this.sap_table_return = "RETURN";
		this.jco_conn  = new Connection();

		//Get SAP BAPI function
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table or Structure
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		JCoStructure jCoStructure = jco_conn.getImportStructure(sap_structure);
		
		MmLivcontractorOutbServ = new MmLivcontractorOutbServices(this.emSynchro);
		List<MmLivcontractorOutb> value_list =  Search();	//MmLivcontractorOutbServ.findAllIsSync("N");
		SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);
	}


//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		
//		try{
//			
//			VwSyncRequestPaymentService obj =new VwSyncRequestPaymentService();
//			obj.Start();
//			
//			
//		}catch(Exception ex)
//		{
//			log.error(ex);
//		}
//
//	}

}
